package com.ypf.survey.service.impl;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.ypf.survey.dao.OptionDAO;
import com.ypf.survey.dao.UserDAO;
import com.ypf.survey.model.Option;
import com.ypf.survey.model.User;
import com.ypf.survey.service.UserService;
import com.ypf.survey.service.dto.UserDto;

public class UserServiceImpl implements UserService {

	@Autowired
	private Mapper mapper;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private OptionDAO optionDAO;
	
	@Override
	public UserDto getUser(Long userId) {
		User user = userDAO.getById(userId);
		return getDto(user);
	}

	@Override
	@Transactional
	public void userAnswer(int [] optionIds, Long userId) {
		User user = userDAO.getById(userId);
		for(int i=0; i< optionIds.length; i++){
			Option option = optionDAO.getById(optionIds[i]);
			user.addAnswer(option);
		}
		
		userDAO.add(user);
	}

	@Override
	public UserDto getByCode(String code) {
		User user = userDAO.getByCode(code);
		return getDto(user);
	}
	
	public boolean userHasAnswered(Long userId){
		return userDAO.userHasAnswered(userId);
	}
	
	private UserDto getDto(User user){
		if(user != null){
			return mapper.map(user, UserDto.class);
		}
		
		return null;
	}

}
